﻿using B.S.Orders.Domain;
using B.S.Orders.ErrorCord;
using B.S.Orders.Read.Api.Application.Commands.DispatchProductCommand;
using B.S.Orders.Read.Api.Application.Commands.OutsourcingCommand;
using B.S.Orders.Read.Api.DTO;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using SqlSugar;

namespace B.S.Orders.Read.Api.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ReportController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly ISqlSugarClient db;

        public ReportController(IMediator mediator, ISqlSugarClient db)
        {
            _mediator = mediator;
            this.db = db;
        }



        /// <summary>
        /// 获取派工信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIResult<APIPaging<DispatchProductDTO>>> GetDispatchProductQuery([FromQuery] GetDispatchProductQueryCommand request)
        {
            return await _mediator.Send(request);
        }
        /// <summary>
        /// 获取派工信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIResult<APIPaging<DispatchProduct>>> GetDispatch([FromQuery] GetDispatchCommand request)
        {
            return await _mediator.Send(request);
        }

        /// <summary>
        /// 根据ID获取派工信息
        /// </summary>
        /// <param name="request">请求</param>
        /// <returns>任务</returns>
        [HttpGet]
        public async Task<APIResult<List<DispatchProduct>>> GetBYIdDispatchProduct([FromQuery] GetBYIdDispatchProductCommand request)
        {
            return await _mediator.Send(request);
        }

        /// <summary>
        /// 根据ID获取派工明细信息
        /// </summary>
        /// <param name="request">请求</param>
        /// <returns>返回任务</returns>
        [HttpGet]
        public async Task<APIResult<List<DispatchDetails>>> GetBYIdDispatchDetails([FromQuery] GetBYIdDispatchDetailsCommand request)
        {
            return await _mediator.Send(request);
        }

        /// <summary>
        /// 查询委外
        /// </summary>
        /// <param name="request">请求</param>
        /// <returns>返回任务</returns>
        [HttpGet]
        public async Task<APIResult<APIPaging<Outsourcing>>> GetOutsourcing([FromQuery] GetOutsourcingCommand request)
        {
            return await _mediator.Send(request);
        }

        /// <summary>
        /// 根据ID查询委外
        /// </summary>
        /// <param name="request">请求</param>
        /// <returns>返回任务</returns>
        [HttpGet]
        public async Task<APIResult<List<Outsourcing>>> GetBYIdOutsourcing([FromQuery] GetBYIdOutsourcingCommand request)
        {
            return await _mediator.Send(request);
        }

        /// <summary>
        /// 根据ID查询委外明细
        /// </summary>
        /// <param name="request">请求</param>
        /// <returns>返回任务</returns>
        [HttpGet]
        public async Task<APIResult<List<OutsourcingDeetail>>> GetBYIdOutsourcingDetails([FromQuery] GetBYIdOutsourcingDetailsCommand request)
        {
            return await _mediator.Send(request);
        }

        /// <summary>
        /// 派工导出方法
        /// </summary>
        /// <returns>返回任务</returns>
        [HttpGet]
        public ActionResult ExportToExcel()
        {
            try
            {
                // 模拟查询数据，这里假设查询 User 表
                var data = db.Queryable<DispatchProduct>().OrderBy(x => x.DispatchProductId).ToList();

                // 创建一个新的 Excel 工作簿
                IWorkbook wb = new XSSFWorkbook();

                //在Excel文件中创建工作表
                ISheet sheet = wb.CreateSheet("派工表");

                //在工作表中创建行(第一行,标题);
                IRow row = sheet.CreateRow(0);

                //创建单元格
                row.CreateCell(0).SetCellValue("派工主键");
                row.CreateCell(1).SetCellValue("单据主题");
                row.CreateCell(2).SetCellValue("单据编号");
                row.CreateCell(3).SetCellValue("来源单据类型");
                row.CreateCell(4).SetCellValue("来源单据");
                row.CreateCell(5).SetCellValue("制单人员");
                row.CreateCell(6).SetCellValue("制单日期");
                row.CreateCell(7).SetCellValue("关联项目");
                row.CreateCell(8).SetCellValue("概要");
                row.CreateCell(9).SetCellValue("订单主键");

                var index = 1;
                foreach (var item in data)
                {
                    row = sheet.CreateRow(index);

                    row.CreateCell(0).SetCellValue(item.DispatchProductId.ToString());
                    row.CreateCell(1).SetCellValue(item.DocumentSubject);
                    row.CreateCell(2).SetCellValue(item.DocumentNumber);
                    row.CreateCell(3).SetCellValue(item.SourceDocumentType);
                    row.CreateCell(4).SetCellValue(item.SourceDocument);
                    row.CreateCell(5).SetCellValue(item.DocumentMakers);
                    row.CreateCell(6).SetCellValue(item.DocumentDate.ToString("yyyy-MM-dd"));
                    row.CreateCell(7).SetCellValue(item.AssociatedProjects);
                    row.CreateCell(8).SetCellValue(item.Outline);
                    row.CreateCell(9).SetCellValue(item.DocumentsId.ToString());

                    index++;
                }

                //Excel的值
                byte[] buffer;
                //通过内存流读出Excel内容,转换为二进制数组
                using (MemoryStream ms = new MemoryStream())
                {
                    wb.Write(ms);
                    buffer = ms.ToArray();
                }

                //导出Excel  using  Microsoft.AspNetCore.StaticFiles;
                string excelMime = new FileExtensionContentTypeProvider().Mappings[".xlsx"];

                //导出
                return File(buffer, excelMime, "派工表.xlsx");
            }
            catch (Exception ex)
            {
                // 处理异常
                Console.WriteLine($"导出 Excel 时出错: {ex.Message}");
            }

            return new EmptyResult();
        }

        /// <summary>
        /// 委外导出方法
        /// </summary>
        /// <returns>返回任务</returns>
        [HttpGet]
        public ActionResult OutExportToExcel()
        {
            try
            {
                // 模拟查询数据，这里假设查询 User 表
                var data = db.Queryable<Outsourcing>().OrderBy(x => x.OutsourcingId).ToList();

                // 创建一个新的 Excel 工作簿
                IWorkbook wb = new XSSFWorkbook();

                //在Excel文件中创建工作表
                ISheet sheet = wb.CreateSheet("委外表");

                //在工作表中创建行(第一行,标题);
                IRow row = sheet.CreateRow(0);

                //创建单元格
                row.CreateCell(0).SetCellValue("委外主键");
                row.CreateCell(1).SetCellValue("单据主题");
                row.CreateCell(2).SetCellValue("单据编号");
                row.CreateCell(3).SetCellValue("关联生产订单");
                row.CreateCell(4).SetCellValue("委外加工商");
                row.CreateCell(5).SetCellValue("客户");
                row.CreateCell(6).SetCellValue("我方代表人");
                row.CreateCell(7).SetCellValue("付款计划");
                row.CreateCell(8).SetCellValue("收票计划");
                row.CreateCell(9).SetCellValue("是否自动收货送检");
                row.CreateCell(10).SetCellValue("是否带料");
                row.CreateCell(11).SetCellValue("委外日期");
                row.CreateCell(12).SetCellValue("制单日期");
                row.CreateCell(13).SetCellValue("制单人员");
                row.CreateCell(14).SetCellValue("关联项目");
                row.CreateCell(15).SetCellValue("备注");
                row.CreateCell(16).SetCellValue("订单主键");

                var index = 1;
                foreach (var item in data)
                {
                    row = sheet.CreateRow(index);

                    row.CreateCell(0).SetCellValue(item.OutsourcingId.ToString());
                    row.CreateCell(1).SetCellValue(item.DocumentSubject);
                    row.CreateCell(2).SetCellValue(item.DocumentNumber);
                    row.CreateCell(3).SetCellValue(item.AssociateProductionOrder);
                    row.CreateCell(4).SetCellValue(item.Processors);
                    row.CreateCell(5).SetCellValue(item.Client);
                    row.CreateCell(6).SetCellValue(item.OurRepresentatives);
                    row.CreateCell(7).SetCellValue(item.PaymentPlan);
                    row.CreateCell(8).SetCellValue(item.TicketCollectionPlan);
                    row.CreateCell(9).SetCellValue(item.AutomaticallyReceivedInspection.ToString());
                    row.CreateCell(10).SetCellValue(item.WhetherMaterials.ToString());
                    row.CreateCell(11).SetCellValue(item.DateOutsourcing.ToString("yyyy-MM-dd"));
                    row.CreateCell(12).SetCellValue(item.PreparationDocumentsDate.ToString("yyyy-MM-dd"));
                    row.CreateCell(13).SetCellValue(item.PreparationDocumentsPerson);
                    row.CreateCell(14).SetCellValue(item.AssociatedProjects);
                    row.CreateCell(15).SetCellValue(item.Remark);
                    row.CreateCell(16).SetCellValue(item.DocumentsId.ToString());

                    index++;
                }

                //Excel的值
                byte[] buffer;
                //通过内存流读出Excel内容,转换为二进制数组
                using (MemoryStream ms = new MemoryStream())
                {
                    wb.Write(ms);
                    buffer = ms.ToArray();
                }

                //导出Excel  using  Microsoft.AspNetCore.StaticFiles;
                string excelMime = new FileExtensionContentTypeProvider().Mappings[".xlsx"];

                //导出
                return File(buffer, excelMime, "委外表.xlsx");
            }
            catch (Exception ex)
            {
                // 处理异常
                Console.WriteLine($"导出 Excel 时出错: {ex.Message}");
            }

            return new EmptyResult();
        }
    }
}
